package com.lebang.service;

import com.alibaba.fastjson.JSON;
import com.lebang.component.RedisClient;
import com.lebang.domain.AppRouseAd;
import com.lebang.example.AppRouseAdExample;
import com.lebang.mapper.AppRouseAdMapper;
import com.lebang.model.RouseModel;
import com.lebang.model.Whether;
import com.lebang.service.sys.DictService;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 数据源排序
 *
 * @Author hwq
 * @Date 2020-03-16
 */
@Service
public class AppRouseAdService extends BaseService<AppRouseAd, Integer, AppRouseAdExample> {
    @Autowired
    private RedisClient redisClient;
    private static final String KEY = "AppRouseAd:";
    public static final String COUNT_KEY = "AppRouseAdCount";
    @Autowired
    private AppRouseAdMapper appRouseAdMapper;
    @Autowired
    private DictService dictService;

    public void initByKey() {
        redisClient.del(KEY);
    }

    public Optional<String> selectAdIdByKey(String key, int count, String appStore) {
        //没设置就用默认渠道
        if (appRouseAdMapper.selectByKeyAndAppStore(key, appStore) == 0) {
            appStore = "all";
        }
        List<AppRouseAd> appRouseAds;
        Optional<String> data = redisClient.Optionalhget(KEY, key + appStore);
        if (data.isPresent()) {
            appRouseAds = JSON.parseArray(data.get(), AppRouseAd.class);
        } else {
            AppRouseAdExample example = new AppRouseAdExample();
            example.setOrderByClause("count desc");
            example.createCriteria().andSdkKeyEqualTo(key)
                    .andHasDeletedEqualTo(Whether.NO.getDbIndex())
                    .andEnableEqualTo(Whether.YES.getDbIndex())
                    .andAppStoreEqualTo(appStore);
            appRouseAds = this.selectByExample(example);
            if (appRouseAds.size() != 0) {
                redisClient.hset(KEY, key + appStore, JSON.toJSONString(appRouseAds));
            }
        }
        if (appRouseAds == null || appRouseAds.size() == 0) {
            return Optional.empty();
        }
        if (dictService.selectIntByKeyName("if_weight_ad_contrl") == 0) {
            for (AppRouseAd next : appRouseAds) {
                if (count >= next.getCount()) {
                    return Optional.ofNullable(next.getAdId());
                }
            }
            return Optional.empty();
        } else {
            List<RouseModel> list = new ArrayList<>();
            for (AppRouseAd s : appRouseAds) {
                int size;
                size = s.getWeight();
                for (int i = 0; i < size; i++) {
                    list.add(new RouseModel(s.getAdId()));
                }
            }
            return Optional.ofNullable(list.get(RandomUtils.nextInt(0, list.size())).getSdkKey());
        }

    }

    /**
     * 返回这个数据源今日的播放量
     *
     * @param key
     * @return
     */
    public int getCountByKey(String key) {
        String now = LocalDate.now().format(DateTimeFormatter.ISO_DATE) + ":";
        Optional<String> str = redisClient.Optionalhget(now + COUNT_KEY, key);
        return str.map(Integer::parseInt).orElse(0);
    }

    /**
     * 播放量+1
     *
     * @param key
     */
    public void addCountByKey(String key) {
        String now = LocalDate.now().format(DateTimeFormatter.ISO_DATE) + ":";
        redisClient.hincrby(now + COUNT_KEY, key, 1L);
        //过期时间修改注释
        //redisClient.expire(now + COUNT_KEY, 86000);
    }
}
